//
//  SSSOnlinePayViewController.m
//  SSSMerchant
//
//  Created by Darker on 2017/3/27.
//  Copyright © 2017年 xnxin. All rights reserved.
//

#import "SSSOnlinePayViewController.h"
#import "WaitModel.h"
#import "SSSOnlinePayCell.h"
#import <AFNetworking/AFNetworking.h>
#import "XHRequestManager.h"
@interface SSSOnlinePayViewController ()<UITableViewDelegate,UITableViewDataSource,UIActionSheetDelegate,UIImagePickerControllerDelegate,UINavigationControllerDelegate>

{
    UITableView *_onlinePayTableView;
    NSArray *_nameArray;
    NSArray *_imageNameArry;
    NSArray *_modelArray;//模型数组
    NSArray *_discArray;
    NSString *_discNuStr;//让利金额
     float i;
    NSString *dateString;
    UIButton *commitBtn;//提交按钮
    UIButton *photoBtn;//相机按钮
    BOOL isFirst;//是否第一次进入
    UIImageView *_photoImageView;//显示图片的视图
    UIImage *_postImage;//
    NSString *_pathStr;
    NSString *_ratioStr;//让利比例
    
}

/** 标签栏当前选中的按钮 */
@property(nonatomic, weak) UIButton *currentBtn;

@end

static NSString *OnlinePauyID    = @"OnlinePauyID";

@implementation SSSOnlinePayViewController

- (void)viewWillAppear:(BOOL)animated{
    
    [super viewWillAppear:animated];
    
    self.title = @"线上支付";
    self.view.backgroundColor = [UIColor colorWithHex:@"F9F9FA"];
    
}

- (void)viewDidLoad {
    [super viewDidLoad];

    isFirst = YES;
    
    UIView *headerView = [UIView new];
    headerView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:headerView];
    headerView.sd_layout
    .leftSpaceToView(self.view,WidthIos6CompeteWithCurrent(15))
    .rightSpaceToView(self.view,WidthIos6CompeteWithCurrent(15))
    .topSpaceToView(self.view,64+HeigthIos6CompeteWithCurrent(15))
    .heightIs(HeigthIos6CompeteWithCurrent(50));
    
    UIView *lineView = [UIView new];
    lineView.backgroundColor = [UIColor colorWithHex:@"E6E6E6"];
    [headerView addSubview:lineView];
    lineView.sd_layout
    .leftSpaceToView(headerView,WidthIos6CompeteWithCurrent(17))
    .rightSpaceToView(headerView,WidthIos6CompeteWithCurrent(17))
    .bottomEqualToView(headerView)
    .heightIs(0.5);
    
    UIImageView *imageView = [UIImageView new];
    [headerView addSubview:imageView];
    imageView.image = [UIImage imageNamed:@"icon_proportion"];
    imageView.sd_layout
    .leftSpaceToView(headerView,WidthIos6CompeteWithCurrent(17))
    .centerYEqualToView(headerView)
    .heightIs(WidthIos6CompeteWithCurrent(20))
    .widthIs(WidthIos6CompeteWithCurrent(20));
    
    //比例
    UILabel *scaleLabel = [UILabel new];
    scaleLabel.text = @"比例:";
    scaleLabel.textColor = [UIColor colorWithHex:@"BBBBBB"];
    scaleLabel.font = [SSSFont systemFontOfSize:13];
    scaleLabel.textAlignment = NSTextAlignmentLeft;
    [headerView addSubview:scaleLabel];
    scaleLabel.sd_layout
    .leftSpaceToView(headerView,WidthIos6CompeteWithCurrent(57))
    .centerYEqualToView(headerView)
    .widthIs(WidthIos6CompeteWithCurrent(200))
    .heightIs(HeigthIos6CompeteWithCurrent(13));
    
    
    NSArray *titleArray = @[@"5%",@"10%",@"20%"];
    CGFloat width = (self.view.frame.size.width - WidthIos6CompeteWithCurrent(147)-WidthIos6CompeteWithCurrent(32))/3;
    CGFloat height = HeigthIos6CompeteWithCurrent(40);
    for (int index = 0; index<titleArray.count; index++) {
        
        UIButton *btn = [[UIButton alloc] initWithFrame:CGRectMake(index * width + WidthIos6CompeteWithCurrent(147),HeigthIos6CompeteWithCurrent(15), width, height)];
        btn.tag = index + 6000;
        // 文字
        [btn setTitle:titleArray[index] forState:UIControlStateNormal];
        
        btn.titleLabel.font = [SSSFont systemFontOfSize:13];
        btn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentCenter;
        // 颜色
        [btn setTitleColor:[UIColor colorWithHex:@"6D6D6D"] forState:UIControlStateNormal];
        // 按钮不能被点击时的颜色
        [btn setTitleColor:[UIColor colorWithHex:@"55A987"] forState:UIControlStateDisabled];
        [btn setImage:[UIImage imageNamed:@"icon_options"] forState:UIControlStateNormal];
        [btn setImage:[UIImage imageNamed:@"icon_pitchon"] forState:UIControlStateDisabled];
        
        // 事件
        [btn addTarget:self action:@selector(discNuBtnClik:) forControlEvents:UIControlEventTouchUpInside];
        [btn sizeToFit];
        [headerView addSubview:btn];
        // 默认选中第一个按钮
        if (index == 0) {
            _ratioStr = [NSString stringWithFormat:@"0.05"];
            btn.enabled = NO;
            self.currentBtn = btn;
            // 让按钮那边的label根据文字内容计算尺寸
            [btn.titleLabel sizeToFit]; // 方法1
            //            self.indicatorView.width = [titles[idx] sizeWithAttributes:@{NSFontAttributeName:btn.titleLabel.font}].width;   // 方法2
            
        }
    }

    //获取但当前日期
    NSDate *currentDate = [NSDate date];//获取当前时间，日期
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"YYYY-MM-dd"];
    dateString = [dateFormatter stringFromDate:currentDate];
    
    //设置数据源
    [self initDataSource];
    
    [self addSubViews];
}
- (void)initDataSource{
    
    _imageNameArry = @[@"icon_time",@"icon_retal",@"icon_profit"];
    
    _nameArray = @[@"时间:",@"总额:",@"应让:"];
    if (isFirst == YES) {
        i = [self.allMoneyStr floatValue] *0.05;
        _discNuStr = [NSString stringWithFormat:@"%0.2f",i];
    }
    _discArray = @[dateString,self.allMoneyStr,_discNuStr];
    
    [_onlinePayTableView reloadData];
    
    NSMutableArray<WaitModel *> *arr =@[].mutableCopy;
    
    for (int index = 0; index < _nameArray.count; index++) {
        
        WaitModel *model = [[WaitModel alloc]init];
        model.titleName = _nameArray[index];
        model.headerImageStr = _imageNameArry[index];
        model.subStr = _discArray[index];
        [arr addObject:model];
    }
    _modelArray = arr.mutableCopy;
    [_onlinePayTableView reloadData];
    isFirst = NO;
}
- (void)addSubViews{
    
    //创建表格
    _onlinePayTableView = [[UITableView alloc]initWithFrame:CGRectMake(WidthIos6CompeteWithCurrent(15),HeigthIos6CompeteWithCurrent(15) + 64 + HeigthIos6CompeteWithCurrent(50),KSCREEN_Width - HeigthIos6CompeteWithCurrent(15)*2,HeigthIos6CompeteWithCurrent(50)*_modelArray.count) style:UITableViewStylePlain];
    _onlinePayTableView.backgroundColor = [UIColor whiteColor];
    _onlinePayTableView.delegate = self;
    _onlinePayTableView.dataSource = self;
    _onlinePayTableView.contentInset = UIEdgeInsetsMake(0, 0, 0, 0);
    _onlinePayTableView.bounces = NO;
    //    _onlinePayTableView.tableHeaderView = _headerView;
    _onlinePayTableView.rowHeight = HeigthIos6CompeteWithCurrent(50);
    _onlinePayTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.view addSubview:_onlinePayTableView];

    
    //上传凭证
    UIView *contentView = [UIView new];
    contentView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:contentView];
    contentView.sd_layout
    .topSpaceToView(_onlinePayTableView,HeigthIos6CompeteWithCurrent(36))
    .leftSpaceToView(self.view,WidthIos6CompeteWithCurrent(15))
    .rightSpaceToView(self.view,WidthIos6CompeteWithCurrent(15))
    .heightIs(HeigthIos6CompeteWithCurrent(181));
    
    photoBtn = [UIButton new];
    [photoBtn setBackgroundImage:[UIImage imageNamed:@"icon_voucher"] forState:UIControlStateNormal];
    [contentView addSubview:photoBtn];
    [photoBtn addTarget:self action:@selector(btnClick) forControlEvents:UIControlEventTouchDown];
    photoBtn.sd_layout
    .centerXEqualToView(contentView)
    .topSpaceToView(contentView,HeigthIos6CompeteWithCurrent(31))
    .heightIs(HeigthIos6CompeteWithCurrent(84))
    .widthIs(WidthIos6CompeteWithCurrent(119));
    
    UILabel *OnlineUploadLabel = [UILabel new];
    OnlineUploadLabel.text = @"上传线下打款凭证";
    OnlineUploadLabel.textColor = [UIColor colorWithHex:@"6D6D6D"];
    OnlineUploadLabel.font = [SSSFont systemFontOfSize:15];
    OnlineUploadLabel.textAlignment = NSTextAlignmentCenter;
    [contentView addSubview:OnlineUploadLabel];
    OnlineUploadLabel.sd_layout
    .topSpaceToView(photoBtn,WidthIos6CompeteWithCurrent(20))
    .centerXEqualToView(contentView)
    .widthIs(WidthIos6CompeteWithCurrent(200))
    .heightIs(HeigthIos6CompeteWithCurrent(15));

    
    
    //显示图片的视图
    _photoImageView = [UIImageView new];
    [contentView addSubview:_photoImageView];
    _photoImageView.sd_layout
    .topSpaceToView(contentView,HeigthIos6CompeteWithCurrent(10))
    .bottomSpaceToView(contentView,HeigthIos6CompeteWithCurrent(10))
    .leftSpaceToView(contentView,WidthIos6CompeteWithCurrent(30))
    .rightSpaceToView(contentView,WidthIos6CompeteWithCurrent(30));
    
    _photoImageView.hidden = YES;
    
    //提交凭证
    commitBtn = [UIButton new];
    [commitBtn setBackgroundColor:[UIColor colorWithHex:@"46B77D"]];
    [commitBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [commitBtn setTitle:@"提 交" forState:UIControlStateNormal];
    commitBtn.titleLabel.font = [SSSFont systemFontOfSize:18];
    [commitBtn addTarget:self action:@selector(commtiBtnClick) forControlEvents:UIControlEventTouchDown];
    [self.view addSubview:commitBtn];
    commitBtn.sd_layout
    .topSpaceToView(contentView,HeigthIos6CompeteWithCurrent(78))
    .centerXEqualToView(self.view)
    .heightIs(HeigthIos6CompeteWithCurrent(51))
    .widthIs(WidthIos6CompeteWithCurrent(290));
    
    commitBtn.layer.cornerRadius = HeigthIos6CompeteWithCurrent(10);
    commitBtn.layer.masksToBounds = YES;
    
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    
    return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    return _modelArray.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    Class currentClass = [SSSOnlinePayCell  class];
    
    SSSOnlinePayCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass(currentClass)];
    if (!cell) {
        cell = [[SSSOnlinePayCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:OnlinePauyID];
    }
    if (indexPath.row == _modelArray.count - 1) {
        cell.lineView.hidden = YES;
    }
    WaitModel *model = _modelArray[indexPath.row];
    cell.onlineModel = model;
    return cell;
}
- (void)discNuBtnClik:(UIButton *)button{
    
    self.currentBtn.enabled = YES;
    button.enabled = NO;
    self.currentBtn = button;
    
    [_onlinePayTableView reloadData];
    
    switch (self.currentBtn.tag - 6000) {
        case 0:
             i = [self.allMoneyStr floatValue] *0.05;
            _discNuStr = [NSString stringWithFormat:@"%0.2f",i];
            [self initDataSource];
            _ratioStr = [NSString stringWithFormat:@"0.05"];
            break;
        case 1:
            i = [self.allMoneyStr floatValue] *0.10;
            _discNuStr = [NSString stringWithFormat:@"%0.2f",i];
            _ratioStr = [NSString stringWithFormat:@"0.15"];
            [self initDataSource];
            break;
        case 2:
            i = [self.allMoneyStr floatValue] *0.20;
            _discNuStr = [NSString stringWithFormat:@"%0.2f",i];
            _ratioStr = [NSString stringWithFormat:@"0.20"];
            [self initDataSource];
            break;
        default:
            break;
    }
    
}
- (void)btnClick{
    
    UIActionSheet * sheet = [[UIActionSheet alloc]initWithTitle:@"请选择" delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:@"相册" otherButtonTitles:@"相机", nil];
    [sheet showInView:self.view];
    
}
#pragma mark - 提交按钮
- (void)commtiBtnClick{
    
    if (_postImage == nil) {
        
        NSString *str = @"请选择你上传凭证照片";
        showTipHudStr(str);
    }else{
        
       // [self reloadUpData];
        //请求图片
        [self reloadUpImageData];
    }
    
}
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    switch (buttonIndex)
    {
        case 0:
        {
            [self getImage:0];
            
        }
            break;
        case 1:
        {
            [self getImage:1];
        }
            break;
            
        default:
            break;
    }
}
#pragma mark - 调用相机或者是相册
- (void)getImage:(int)sender
{
    NSUInteger sourceType = 0;
    switch (sender)
    {
        case 0:
            // 照片
            sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
            break;
        case 1:
        {
            // 相机
            
            NSString *mediaType = AVMediaTypeVideo;
            AVAuthorizationStatus authStatus =[AVCaptureDevice authorizationStatusForMediaType:mediaType];
            if (authStatus ==  AVAuthorizationStatusDenied)
            {
                UIAlertView * alertView=[[UIAlertView alloc]initWithTitle:@"" message:@"请在iPhone的“设置-隐私-相机”选项中,允许App访问您的相机" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil];
                [alertView show];
                return;
            }
            else
            {
                if([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera])
                {
                    sourceType = UIImagePickerControllerSourceTypeCamera;
                    break;
                }
            }
            
        }
        default:
            break;
    }
    // 跳转到相机或相册页面
    UIImagePickerController *picker = [[UIImagePickerController alloc] init];
    picker.delegate = self;
    picker.allowsEditing = YES;
    picker.sourceType = sourceType;
    [self presentViewController:picker animated:YES completion:nil];
    
}
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info{
    
    UIImage * image = [info objectForKey:UIImagePickerControllerEditedImage];
    _photoImageView.hidden = NO;
    //[photoBtn setBackgroundImage:image forState:UIControlStateNormal];
    _photoImageView.image = image;
    _postImage = image;
    //从相机或相册页面返回
    [self dismissViewControllerAnimated:YES completion:nil];

}
- (void)reloadUpData{
    
//    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:_idArray options:NSJSONWritingPrettyPrinted error:nil];
//    NSString *idArrayJsonStr = [[NSString alloc]initWithData:jsonData encoding:NSUTF8StringEncoding];
//    NSMutableString *idJsonStr = [NSMutableString stringWithString:idArrayJsonStr];
//    NSRange range = {0,idArrayJsonStr.length};
//    //去掉字符串中的空格
//    [idJsonStr replaceOccurrencesOfString:@" " withString:@"" options:NSLiteralSearch range:range];
//    NSRange range2 = {0,idJsonStr.length};
//    //去掉字符串中的换行符
//    [idJsonStr replaceOccurrencesOfString:@"\n" withString:@"" options:NSLiteralSearch range:range2];
    NSString *idJsonStr = [_idArray componentsJoinedByString:@","];
    XHLog(@"--idArrayStr--%@",idJsonStr);
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    params[@"ids"] = idJsonStr;
    params[@"rangli"] = _ratioStr;
    params[@"voucherPic"] = _pathStr;
    
    [[XHRequestManager manager] postRequest:kConfigPath(kOrderPendingCommit) params:params success:^(id  _Nonnull response) {
        XHLog (@"----response---%@",response);
        if ([response[@"status"] intValue] == 0 ) {
            
            [QMUITips showSucceed:@"提交成功" inView:self.view hideAfterDelay:2];
            
        }else{
            
            [QMUITips showError:response[@"message"] inView:self.view hideAfterDelay:2];
        }
    } failure:^(NSError * _Nonnull error) {
        
        XHLog(@"%@",error.localizedDescription);
        [QMUITips showError:error.localizedDescription inView:self.view hideAfterDelay:2];
    }];

}
- (void)reloadUpImageData{
    
    
     NSData *data1 = UIImageJPEGRepresentation(_postImage, 0.5f);
    
    NSMutableURLRequest *request = [[AFHTTPRequestSerializer serializer] multipartFormRequestWithMethod:@"POST"
                                                                                              URLString:kConfigPath(kImageCommit)
                                                                                             parameters:nil
                                                                              constructingBodyWithBlock:
                                    ^(id<AFMultipartFormData> formData)
                                    {
  
    [formData appendPartWithFileData:data1 name:@"files" fileName:@"filename.jpg" mimeType:@"image/*"];
                                        } error:nil];
    
    [request setValue:[SSSUserManager getUserModel].token forHTTPHeaderField:@"token"];
    
    AFHTTPSessionManager *manager = [[AFHTTPSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
    manager.requestSerializer = [AFJSONRequestSerializer serializer];
    
    NSURLSessionUploadTask *uploadTask;
    uploadTask = [manager
                  uploadTaskWithStreamedRequest:request
                  progress:nil
                  completionHandler:^(NSURLResponse * _Nonnull response, id  _Nullable responseObject, NSError * _Nullable error) {
                      if (error) {
                          NSLog(@"Error: %@", error);
                      } else {
                          NSLog(@"%@ %@", response, responseObject);
                          _pathStr = responseObject[@"data"][@"path"];
                         //上传表单
                        [self reloadUpData];
                      }
                  }];
    
    [uploadTask resume];

}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
